package com.springboot.demo.thread;

import org.junit.Test;

/**
 * 线程demo
 *
 * @author supu
 * @date 2019-04-08 13:43
 **/
public class ThreadDemo {
    @Test
    public void test() {
        Poller poller = new Poller();

        Thread pollerThread = new Thread(poller, "pollerThread");
        pollerThread.setPriority(Thread.NORM_PRIORITY);
        pollerThread.setDaemon(true);
        pollerThread.start();
    }

    @Test
    public void testThreadInterrupt(){
        Thread t = new MyThread();
        t.start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
        System.out.println("main end");
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            //非阻塞过程中通过判断中断标志来退出
            for (int i = 0; i < 10; i++) {
                System.out.println("循环次数 ：" + i);
                for(int j =0; j < 10000; j++){
                    System.out.println("");
                }
            }
           /* while (!isInterrupted()){
                System.out.println("myThread is running");
                int index = 0;
                for(int i =0; i < 10000; i++){
                    index++;
                    System.out.print("");
                }
                System.out.println("end, index : " + index);
                //非阻塞过程中通过判断中断标志来退出
                *//*try{
                    System.out.println("start");
                    Thread.sleep(5*1000);//阻塞过程捕获中断异常来退出
                    System.out.println("end");
                }catch(InterruptedException e){
                    e.printStackTrace();
                    break;//捕获到异常之后，执行break跳出循环。
                }*//*
            }*/
            System.out.println("myThread over");
        }
    }

    class Poller implements Runnable {
        @Override
        public void run() {
            System.out.println(" run is coming");
            int index = 0;
            for (; ; ) {
                index++;
                System.out.println("index:" + index);
                if (index == 3) {
                    break;
                }
                System.out.println("threadName:" + Thread.currentThread().getName() + ", poller is run");
            }

            /*while (true) {
                index++;
                System.out.println("index:" + index);
                if (index == 3) {
                    break;
                }
                System.out.println("threadName:" + Thread.currentThread().getName() + ", poller is run");
            }*/
        }
    }
}
